package com.wx.spider.pc.controller;

import com.wx.spider.common.enums.MqMsgBean;
import com.wx.spider.common.model.CommonResponse;
import com.wx.spider.common.model.Constants;
import com.wx.spider.common.pojo.db.WxBiz;
import com.wx.spider.common.util.StringUtil;
import com.wx.spider.pc.config.CloudConfig;
import com.wx.spider.pc.feign.SqlWsClient;
import com.wx.spider.pc.service.WxBizService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author:feng
 * @create:2021-04-23 12:09
 */
@RestController
@RequestMapping("/wxbiz")
@Slf4j
public class WxbizController {
    @Autowired
    private CloudConfig cloudConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SqlWsClient sqlWsClient;

    @Autowired
    public RocketMQTemplate rocketMQTemplate;

    @Autowired
    private WxBizService wxBizService;

    @RequestMapping("/test")
    private CommonResponse<String> test() {
        System.out.println(cloudConfig.getUsername());
        return CommonResponse.SUCCESS_RESPONSE;
    }


    @RequestMapping(value = "/pushLink", produces = "application/json; charset=utf-8")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public CommonResponse pushLink(String link) {
        try {
            System.out.println("获取历史消息链接成功");
            System.out.println(link);

            Map<String, String> paramMap = StringUtil.getAllParam(link.replace("==", "######"));

            String biz = paramMap.get("__biz").replace("######", "==");
            WxBiz wxBiz = sqlWsClient.findWxBizByBiz(biz).getData();
            if (wxBiz == null) {
                log.info("公众号已不存在爬虫列表：{}", biz);
                return CommonResponse.SUCCESS_RESPONSE;
            }

            wxBizService.spiderBiz(paramMap, wxBiz);

            return CommonResponse.SUCCESS_RESPONSE;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    @GetMapping(value = "/push")
    @CrossOrigin(origins = "*", maxAge = 3600)
    private CommonResponse rightPush(String bizs) {

        try {
            if (bizs != null) {
                String[] urlArray = bizs.split(",");
                stringRedisTemplate.opsForList().leftPushAll(Constants.WX_BIZ_GET_LIST_QUNUE, urlArray);
            } else {
                String urlArray[] = new String[1];
                urlArray[0] = "MzIzOTAzMzkyNg==";
                stringRedisTemplate.opsForList().leftPushAll(Constants.WX_BIZ_GET_LIST_QUNUE, urlArray);
            }

            System.out.println(stringRedisTemplate.opsForList().range(Constants.WX_BIZ_GET_LIST_QUNUE, 0, -1));
            return CommonResponse.SUCCESS_RESPONSE;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }

    }

    @GetMapping(value = "/pushAll")
    @CrossOrigin(origins = "*", maxAge = 3600)
    private CommonResponse pushAll() {

        try {
            List<WxBiz> list = sqlWsClient.findAllWxBiz().getData();

            for (WxBiz wxBiz : list) {
                stringRedisTemplate.opsForList().rightPush(Constants.WX_BIZ_GET_LIST_QUNUE, wxBiz.getBiz());
            }
            System.out.println(stringRedisTemplate.opsForList().range(Constants.WX_BIZ_GET_LIST_QUNUE, 0, -1));
            rocketMQTemplate.convertAndSend(MqMsgBean.PM_TO_JAVA_SOCKET.getTopic(), "start tasks!");
            return CommonResponse.SUCCESS_RESPONSE;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }

    }

    /**
     * 获取任务
     *
     * @return
     */
    @GetMapping("/wxBizTask")
    @CrossOrigin(origins = "*", maxAge = 3600)
    private CommonResponse<Map<String, String>> wxBizTask() {
        try {

            WxBiz wxBiz = null;
            while (stringRedisTemplate.opsForList().size(Constants.WX_BIZ_GET_LIST_QUNUE) > 0) {
                String biz = stringRedisTemplate.opsForList().leftPop(Constants.WX_BIZ_GET_LIST_QUNUE);
                //双重校验
                if (biz != null) {
                    CommonResponse<WxBiz> bizRes = sqlWsClient.findWxBizByBiz(biz);
                    wxBiz = bizRes.getData();
                }

                if (wxBiz != null) {
                    break;
                }
            }

            HashMap<String, String> map = new HashMap<>();

            if (wxBiz == null) {
                map.put("msg", "noTask");
            } else {
                String url = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=" + wxBiz.getBiz();
                map.put("url", url);
                map.put("name", wxBiz.getName());
            }

            return CommonResponse.succeed(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    /**
     * 获取随机睡眠时间
     *
     * @return
     */
    @GetMapping("/randomSleepTime")
    @CrossOrigin(origins = "*", maxAge = 3600)
    private CommonResponse<Integer> randomSleepTime() {
        try {
            Random random = new Random();
            Integer min = cloudConfig.getMinSleepTimeGetList() == null ? 10 : cloudConfig.getMinSleepTimeGetList();
            Integer max = cloudConfig.getMaxSleepTimeGetList() == null ? 60 : cloudConfig.getMaxSleepTimeGetList();

            int sleepTime = random.nextInt(max - min) + min;
            CommonResponse<Integer> result = new CommonResponse<Integer>("0000", "success");
            result.setData(sleepTime);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    /**
     * 获取剩余任务数和当前账号24小时内已执行的次数
     *
     * @return
     */
    @GetMapping("/getQunueSize/{phone}")
    @CrossOrigin(origins = "*", maxAge = 3600)
    private CommonResponse<Map<String, Long>> getQunueSize(@PathVariable("phone") String phone) {
        try {

            if (phone == null || "".equals(phone)) {
                return CommonResponse.PARAM_ERROR_RESPONSE;
            }

            //判断当前账号24H内已执行页数
            String key = Constants.WX_BIZ_GET_LIST_ACCOUNT + phone;
            //获取24H前时间戳
            long before24H = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
            //移除24H之前爬取的记录
            while (stringRedisTemplate.opsForList().size(key) > 0) {
                Long value = Long.valueOf(stringRedisTemplate.opsForList().index(key, 0));
                if (value < before24H) {
                    stringRedisTemplate.opsForList().leftPop(key);
                } else {
                    break;
                }
            }

            HashMap<String, Long> map = new HashMap<>();
            Long qunueSize = stringRedisTemplate.opsForList().size(Constants.WX_BIZ_GET_LIST_QUNUE);
            map.put("qunueSize", qunueSize);
            Long runCount = stringRedisTemplate.opsForList().size(key);
            map.put("runCount", runCount);

            CommonResponse<Map<String, Long>> result = new CommonResponse<Map<String, Long>>("0000", "success");
            result.setData(map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }
}
